$(function () {

    var roomid="";
    var token="";
    var  teacherCode ="";
    var  ptcode ="";
    var id = "";

    //初始化专业
    $.initSubject({
        element:'subject-box',
        confirmBtn:false,
        removeBtn: false,
        style:false,
        notMultiple:true,
        classText:'form-control',
        width:100,
        selectCallback:function(subjectIds){
            $("#subjectIds").val(subjectIds);
        }
    });

    var clipboard = new Clipboard('#clone');

    clipboard.on('error', function () {
        icModale(0, '复制链接失败');
    });
    clipboard.on('success', function() {
        icModale(0, '复制链接成功');
    });

    $("body").on('click','#courseOpen-list-context i.fa-video-camera',function () {//直播人员开始直播
        id = $(this).parent().data('id');
        var type = $(this).parent().data('type');
        roomid= $(this).parent().data('room');
        if(type=="CC"){
            //今日直播调起选择直播身份和下载直播客户端
            teacherCode = $(this).parent().data('teachercode');
            token=$(this).parent().data('admincode');
            ptcode=$(this).parent().data('ptcode');
            liverOpenOptionsFnByCC();
        }else if(type=="TT"){
            liverOpenOptionsFnByTT();
        }else{
            $.ajax({
                url: baseloaction + '/admin/course/open/live/start',
                data: {'id': id},
                dataType: 'json',
                success: function (response) {
                    if (response.success==true) {
                        if(type=='96K'){
                            clientTips();
                        }
                        var client = window.open(response.entity, '_blank');
                        setTimeout(function() {
                            if (client) {
                                client.close();
                            }
                        }, 5000);
                    } else {
                        icModale(0, response.message);
                    }
                }
            })

        }
    }).on('click','#courseOpen-list-context i.fa-eye',function () {//查看详情
        var id = $(this).parent().data('id');
        var courseName = $("#course-open-name-"+id).text();
        parent.layer.open({
            type: 2,
            shadeClose: false,
            shade: [0.3, '#000000'],
            title: '<strong>查看免费直播详情【' + courseName + '】</strong>',
            area: ['800px', '500px'],
            content: baseloaction + "/admin/course/open/showCourseOpenInfo?id=" + id,
            btn: ['进入修改状态', '取消'],
            yes: function (index, layero) {
                window.location.href = baseloaction + '/admin/course/open/initUpdate?id='+id;
                parent.layer.close(index);
            }
        });
    }).on('click','#courseOpen-list-context i.fa-unlock-alt',function () {//单个冻结
        var id = $(this).parent().data('id');
        updateCourseOpen(id,2);
    }).on('click','#courseOpen-list-context i.fa-history',function () {//单个恢复
        var id = $(this).parent().data('id');
        updateCourseOpen(id,1);
    }).on('click','#courseOpen-list-context i.fa-trash-o',function () {//单个删除
        var id = $(this).parent().data('id');
        updateCourseOpen(id,3);
    }).on('click','#courseOpen-list-context i.fa-clone',function () {//复制链接
        var $this = $(this);
        var type = $(this).parent().data('type');
        if(type=="CC"){
            var roomid = $(this).parent().data('room');
            var teachercode = $(this).parent().data('teachercode');
            var teachername = $(this).parent().data('teachername');
            window.location.href =  "cclive://"+ccAppId+"/"+roomid+"/"+teachername+"/"+teachercode;
            return;
        }
        var anchor = $this.parent().data('teachercode');
        var sign = $this.parent().data('sign');
        var room = $this.parent().data('room');
        var admincode = $this.parent().data('admincode');
        var studentcode = $this.parent().data('studentcode');


        $('#anchor').text('https://www.96koo.net/common/live/Login.php?account=' + room + '&role=anchor&password=' + anchor + '&type=1&sign=' + sign);
        $('#assistant').text('https://www.96koo.net/common/live/Login.php?account=' + room + '&role=admin&type=2&sign=' + sign+"&password="+admincode);
        $('#limit').text('https://www.96koo.net/common/live/Login.php?account=' + room + '&role=user&type=0&sign=' + sign+"&password="+studentcode);
        $('#free').text('https://www.96koo.net/common/live/loginf.php?account=' + room + '&role=user&freepassword=1&type=0&sign=' + sign);
        $('#anchor, #assistant, #limit, #free').prop('readonly', true);
        parent.layer.open({
            type: 1,
            area: ['800px', '400px'],
            skin: 'layui-layer-demo',
            title: '<strong>复制链接</strong>',
            content: $('#copy-url-tips').html(),
            btn: ['复制', '取消'],
            shadeClose: true,
            yes: function (index, layero) {
                clipboard.text = function() {
                    return layero.find('div[id^=tab].active textarea').val();
                };
                $('#clone').click();
            },
            btn2: function () {
                parent.layer.closeAll()
            }
        })
    }).on('click','#freezeBatch',function () {//批量冻结
        var ids = obtainIds(2);
        if(ids!=null){
            updateCourseOpen(ids,2);
        }
    }).on('click','#restoreBatch',function () {//批量恢复
        var ids = obtainIds(1);
        if(ids!=null){
            updateCourseOpen(ids,1);
        }
    }).on('click','#deleteBatch',function () {//批量删除
        var ids = obtainIds(3);
        if(ids!=null){
            updateCourseOpen(ids,3);
        }
    }).on('click','#btn1,#btn2',function () {
        getCourseOpenData(1);
    });

    function setButtonInfo() {
        var platform = (navigator.platform || '').toLowerCase();
        if (platform.indexOf('win') != -1) {
            $('.download').data('link', 'https://c1.96koo.net/package/zhinengzhibo6.9.0.zip').html('下载');
        } else if (platform.indexOf('mac') != -1) {
            $('.download').data('link', 'https://c1.96koo.net/package/zhinengzhibomac6.9.2.dmg').html('下载');
        }
    }
    function clientTips() {
        setButtonInfo();
        var _ele = $('#sysItemLiveEle').html();
        var index = parent.layer.open({
            type: 1,
            area: ['450px', '210px'],
            skin: 'layui-layer-demo',
            title: '讲师进入直播',
            content: _ele,
            success: function (a) {
                a.find('.download').click(function () {
                    var platform = (navigator.platform || '').toLowerCase();
                    if (platform.indexOf('win') != -1) {
                        window.open('https://c1.96koo.net/package/zhinengzhibo6.8.0.zip', "_blank");
                    } else if (platform.indexOf('mac') != -1) {
                        window.open('https://c1.96koo.net/package/zhinengzhibomac6.8.0.dmg', "_blank");
                    }
                    parent.layer.close(index);
                });
                a.find('.cancel').click(function () {
                    parent.layer.close(index);
                })
            }
        });
    }

    //今日直播调起选择直播身份和下载直播客户端
    function liverOpenOptionsFnByCC() {
        var _ele = $('#sysItemLiveTipsEleByCC').val()
        parent.layer.open({
            type: 1,
            area: ['860px', '600px'],
            content: _ele,
            shade: [0.3, '#000'],
            shadeClose: false,
            title: '今日直播',
            success: function (layero, index) {
                layero.find('[data-toggle="tooltip"]').tooltip();
                layero.find("#theHostLive").on("click",function(){
                    openInputNameByCC(1);
                });
                layero.find("#theTeacherLive").on("click",function(){
                    openInputNameByCC(2);
                });
                layero.find("#theTaLive").on("click",function(){
                    openInputNameByCC(3);
                });
            }
        });
    }


    function  openInputNameByCC(type){
        var _ele = $('#openInputName').val()
        parent.layer.open({
            type: 1,
            area: ['240px','180px'],
            skin: 'layui-layer-demo',
            title: '<strong>请输入姓名</strong>',
            content: _ele,
            btn: '确定',
            yes: function(index, layero) {
                var pass = layero.find('#rejectedCause').val();
                if(pass.length<=0){
                    icModale(0, '请填写姓名');
                    return  ;
                }
                if(pass.length>=30){
                    icModale(0, '姓名不能大于30个字符');
                    return  ;
                }
                icModale(0, '进入中');

                if(type==1){
                    var url ="https://view.csslcloud.net/api/view/index?roomid="+roomid+"&userid="+ccAppId+"&autoLogin=true&viewername="+pass+"&autoLogin=true&viewertoken="+ptcode;
                    window.open(url,"_blank");
                }
                if(type==2){
                    window.location.href =  "cclive://"+ccAppId+"/"+roomid+"/"+pass+"/"+teacherCode;
                }

                if(type==3){
                    var url ="https://view.csslcloud.net/api/view/assistant?viewername="+pass+"&roomid="+roomid+"&userid="+ccAppId+"&autoLogin=true&viewertoken="+token;
                    window.open(url,"_blank")
                }

                icModale(0, '进入中');
                parent.layer.closeAll();

            }
        });
    }

    //今日直播调起选择直播身份和下载直播客户端
    function liverOpenOptionsFnByTT() {
        var _ele = $('#sysItemLiveTipsEleByTT').val()
        parent.layer.open({
            type: 1,
            area: ['860px', '600px'],
            content: _ele,
            shade: [0.3, '#000'],
            shadeClose: false,
            title: '今日直播',
            success: function (layero, index) {
                layero.find('[data-toggle="tooltip"]').tooltip();
                layero.find("#theTeacherLiveClient").on("click", function () {
                    openInputNameByTT(1,id,1);
                });
                layero.find("#theTeacherLiveWebPage").on("click", function () {
                    openInputNameByTT(1, id,2);
                });
                layero.find("#theTaLiveClient").on("click", function () {
                    openInputNameByTT(2, id,1);
                });
                layero.find("#theTaLiveWebPage").on("click", function () {
                    openInputNameByTT(2, id,2);
                });
                layero.find("#theHostLiveClient").on("click", function () {
                    openInputNameByTT(3, id,1);
                });
                layero.find("#theHostLiveWebPage").on("click", function () {
                    openInputNameByTT(3, id,2);
                });
            }
        });
    }

    function openInputNameByTT(type,id,openType){
        parent.layer.closeAll();
        if (openType == '1') {
            parent.layer.open({
                content: '进入前需安装直播客户端，如已安装可点击进入即可！'
                ,title: '友情提示'
                , btn: ['进入直播间', '下载客户端']
                , yes: function (index, layero) {
                    toLive(type, id, openType);
                }, btn2: function (index, layero) {
                    window.location.href = "https://ftp.3ttech.cn/云中课堂.exe";
                }, cancel: function () {
                }
            });
        } else {
            toLive(type,id,openType)
        }
    }

    function toLive(type, id, openType) {
        var liveUrl = "";
        var _ele = $('#openInputName').val();
        if (type != 3) {
            parent.layer.closeAll();
            $.ajax({
                url: baseloaction + '/admin/liveToV/create/getLiveParam',
                data: {'type': type, 'courseOpenId': id, 'selectType': 'courseOpen'},
                dataType: 'json',
                success: function (result) {
                    if (result.success == true) {
                        if (openType == '1') {
                            liveUrl = "yzkt://quickenterlive&i=" + result.entity.UID + "&k=" + result.entity.safeKey + "&t=" + result.entity.timeStamp + "&r=" + result.entity.classId + "";
                            window.protocolCheck(
                                liveUrl,
                                function () {
                                    icModale(0, "客户端软件未安装");
                                }
                            );
                            event.preventDefault ? event.preventDefault() : event.returnValue = false;
                        } else {
                            var url = result.entity.classRoomUrl;
                            $("#url").val(url);
                            $("#toLiveIframe").submit();
                        }
                    } else {
                        icModale(0, result.message);
                    }
                }
            });
        } else {
            var html = '请输入账号';
            parent.layer.open({
                type: 1,
                area: ['240px', '180px'],
                skin: 'layui-layer-demo',
                title: '<strong>' + html + '</strong>',
                content: _ele,
                btn: '确定',
                yes: function (index, layero) {
                    var pass = layero.find('#rejectedCause').val();
                    if (pass.length <= 0) {
                        icModale(0, html);
                        return;
                    }
                    if (pass.length >= 30) {
                        icModale(0, '不能大于30个字符');
                        return;
                    }
                    icModale(0, '进入中');
                    $.ajax({
                        url: baseloaction + '/admin/liveToV/create/getLiveParam',
                        data: {'type': type, 'courseOpenId': id, 'selectType': 'courseOpen', 'name': pass},
                        dataType: 'json',
                        success: function (result) {
                            parent.layer.closeAll();
                            if (result.success == true) {
                                if (openType == '1') {
                                    liveUrl = "yzkt://quickenterlive&i=" + result.entity.UID + "&k=" + result.entity.safeKey + "&t=" + result.entity.timeStamp + "&r=" + result.entity.classId + "";
                                    window.protocolCheck(
                                        liveUrl,
                                        function () {
                                            icModale(0, "客户端软件未安装");
                                        }
                                    );
                                    event.preventDefault ? event.preventDefault() : event.returnValue = false;
                                } else {
                                    var url = result.entity.classRoomUrl;
                                    $("#url").val(url);
                                    $("#toLiveIframe").submit();
                                }
                            } else {
                                icModale(0, result.message);
                            }
                        }
                    });
                }
            });
        }
    }
    getCourseOpenData(1);
    /**
     * 获取免费直播数据列表
     * @param pageNo
     */
    function getCourseOpenData(pageNo) {
        var params = $("#search-form").serializeJSON();
        params = JSON.stringify(params);
        var obj = {
            url: baseloaction + '/admin/course/open/ajaxCourseOpenList',//请求URL
            contextId: 'courseOpen-list-context',//响应内容页面设置内容ID
            params: params,//请求参数
            pageNo: pageNo,//页码
            pageCall: getCourseOpenData, //分页回调加载数据(点击上下页时调用,该方法也在加载页面完成时调用)
            selectAllId: 'select-all-courseOpen', //全选框ID
            callback: function () {//数据加载完成回调
                $("#count").html('(共'+total+'个模块)');
            }
        };
        ajaxGetListData(obj);
    }

    /**
     * 修改状态
     * @param ids
     * @param status
     */
    function updateCourseOpen(ids,status) {
        var message ="";
        if(status==1){
            message = "确认要恢复选中免费直播数据？";
        }
        if(status==2){
            message = "确认要冻结选中免费直播数据？";
        }
        if(status ==3){
            message = "确认要删除选中免费直播数据？";
        }
        icModale(2, message, 3, function () {
            $.ajax({
                url:baseloaction +'/admin/course/open/updateCourseOpenStatus',
                type:'post',
                dataType:'json',
                data:{'ids':ids,'status':status},
                success:function (result) {
                    if(result.success==true){
                        var arr = (ids+'').split(",");
                        $.each(arr,function (index,id) {
                            var statusEm = $("#open-status-"+id);
                            var statusAction = $("#status-action-"+id);
                            if(status==1){
                                statusEm.html('<span class="label label-info">正常</span>');
                                statusAction.html('<i class="fa fa-unlock-alt"></i>');
                                statusAction.attr('data-original-title','冻结');
                            }
                            if(status==2){//冻结
                                statusEm.html('<span class="label label-danger">冻结</span>');
                                statusAction.html('<i class="fa fa-history"></i>');
                                statusAction.attr('data-original-title','恢复');
                            }
                            if(status==3){//删除
                                $("#course-open-"+id).remove();
                            }
                        });
                    }else{
                        icModale(0,result.message);
                    }
                },
                error:function (error) {
                    icModale(0,'系统错误，操作失败');
                }
            });
        });
    }

    /**
     * 获取勾选ID是否为空
     * @param obj
     * @return {*}
     */
    function obtainIds(status) {
        var obj = $('input[name="courseOpenId"]:checked');
        if(obj.length <= 0){
            if(status==1){
                icModale(0,"请选择要恢复的数据");
            }
            if(status==2){
                icModale(0,"请选择要冻结的数据");
            }
            if(status==3){
                icModale(0,"请选择要删除的数据");
            }
            return null;
        }else {
            var courseOpenIds = obj.map(function () {
                return this.value;
            }).get().join(",");
            return courseOpenIds;
        }
    }
});

var clipboard = new Clipboard('#clone');

clipboard.on('error', function () {
    icModale(0, '复制链接失败');
});

clipboard.on('success', function () {
    icModale(0, '复制链接成功');
});